package com.yjt.oauth.service;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yjt.common.constant.ComConstant;
import com.yjt.common.entity.oauth.CommonUser;
import com.yjt.common.vo.UserDetailVO;
import com.yjt.oauth.dao.EmplyMapper;
import com.yjt.oauth.entity.Emply;
import com.yjt.oauth.form.LoginForm;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.springframework.beans.BeanUtils;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 曾智平
 * @Description: 重写登录认证功能
 * @date 2021/7/7 16:29
 */
@Service
public class OauthSysUserDetailsService implements UserDetailsService {

    @Resource
    private EmplyMapper emplyMapper;

    @Override
    public UserDetails loadUserByUsername(String username) {
        //根据登录平台判断是app用户还是后台用户
        LoginForm loginForm = JSONObject.parseObject(username, LoginForm.class);
        if (ComConstant.LOGINPLATFORM[0].equalsIgnoreCase(loginForm.getPlatform())) {
            //后台登录
            return getAdminUserInfo(loginForm.getUsername());
        }
        if (ComConstant.LOGINPLATFORM[1].equalsIgnoreCase(loginForm.getPlatform())) {
            //App登陆
            return null;
        }
        return null;
    }

    /**
     * 获取用户信息
     *
     * @param username
     * @return
     */
    private UserDetailVO getAdminUserInfo(String username) {
//        //解决缓存获取不到的情况
//        TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), Emply.class);
        // 获取用户
        LambdaQueryWrapper<Emply> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(Emply::getEmplyId, Emply::getEmplyName, Emply::getPwd)
                .eq(Emply::getLogonName, username);
        Emply emplyPo = emplyMapper.selectOne(queryWrapper);
        // 用户不存在
        if (emplyPo == null) {
            throw new InternalAuthenticationServiceException("用户不存在");
        }
        CommonUser commonUser = new CommonUser();
        BeanUtils.copyProperties(emplyPo, commonUser);
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        return new UserDetailVO(commonUser, authorities);
    }


}
